package com.chaoli.reggie_diy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaoli.reggie_diy.common.R;
import com.chaoli.reggie_diy.domain.Category;
import com.chaoli.reggie_diy.domain.Dish;
import com.chaoli.reggie_diy.domain.DishFlavor;
import com.chaoli.reggie_diy.dto.DishDto;
import com.chaoli.reggie_diy.service.CategoryService;
import com.chaoli.reggie_diy.service.DishFlavorService;
import com.chaoli.reggie_diy.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> addDish(@RequestBody DishDto dishDto) {
        log.info("DishDto封装的数据：{}", dishDto.toString());
        dishService.saveWithFlavor(dishDto);

        // 清理所有redis缓存
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        // 清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return null;
    }

    /**
     * 菜品数据分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(@RequestParam Long page, @RequestParam Long pageSize, String name) {
        // 因为页面需要菜品分类的字段，但是在Dish类中只有categoryId
        // 所以根据categoryId找到对应的菜品分类，然后封装成page对象传给前端
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name)
                .orderByDesc(Dish::getUpdateTime);
        //查询dish表
        dishService.page(dishPage, queryWrapper);
        ////拷贝分页信息
        //拷贝的是page对象的属性，不是实体类中的属性
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        //page对象中包含的实体类属性处理
        List<Dish> dishList = dishPage.getRecords();
        List<DishDto> dishDtoList = dishList.stream().map((dish) -> {
            DishDto dishDto = new DishDto();
            //拷贝展示的数据信息
            BeanUtils.copyProperties(dish, dishDto);
            Category category = categoryService.getById(dish.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);

    }

    /**
     * 根据id查询菜品信息和口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getDishAndFlavorById(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        // 清理所有redis缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        // 清理某个分类下面的菜品缓存数据
//        String key = "dish_"+dishDto.getCategoryId()+"_1";
//        redisTemplate.delete(key);

        return R.success("修改成功");
    }

    /**
     * 根据条件查询菜品数据
     * <p>
     * 为什么用dish来接收传来的categoryId？
     * Dish中有categoryId字段，可以接收
     * 并且传递过来Dish中的其他参数，也能接收，增加通用性
     *
     * @param dish
     * @return
     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish) {
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
//                .eq(Dish::getStatus, 1)
//                .orderByDesc(Dish::getUpdateTime)
//                .orderByDesc(Dish::getSort);
//
//        List<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }
    //对上面方法的改进
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;
        // 动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        // 先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }
//        如果不存在，查询数据库
        // 构造查询条件
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish::getStatus, 1)
                .orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(dishQueryWrapper);
        dishDtoList = dishList.stream().map(oldDish -> {
            DishDto newDishDto = new DishDto();
            BeanUtils.copyProperties(oldDish, newDishDto);
            Category category = categoryService.getById(dish.getCategoryId());
            if (category != null) {
                newDishDto.setCategoryName(category.getName());
            }
            LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorQueryWrapper.eq(DishFlavor::getDishId, oldDish.getId());
            // select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorQueryWrapper);
            newDishDto.setFlavors(dishFlavorList);
            return newDishDto;
        }).collect(Collectors.toList());
        //将查询到的数据缓存到redis，设置过期时间为1小时
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);


    }

    /**
     * 菜品的启售和停售
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable(value = "status") Integer status, @RequestParam(value = "ids") List<Long> ids) {
        List<Dish> dishList = dishService.listByIds(ids);

        for (Dish dish : dishList) {
            if (dish == null) {
                return R.error("售卖状态异常");
            }
            dish.setStatus(status);
            dishService.updateBatchById(dishList);
        }
        return R.success("操作成功");

    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam(value = "ids") List<Long> ids) {
        log.info(ids.toString());
        return dishService.deleteByIdsPerfect(ids);
    }


}
